package com.piece.file.preview;

import com.piece.core.framework.constant.ExceptionConstants;
import com.piece.core.framework.exception.ServerException;
import com.piece.core.framework.util.basic.I18nUtil;
import com.piece.core.framework.util.file.FileUtil;
import com.piece.core.web.util.ServletUtil;
import com.piece.file.support.FileAttribute;
import com.piece.file.client.FileClientFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 处理office文件
 */
@Slf4j
@Service
@RefreshScope
public class OfficeFilePreview implements FilePreviewHandle {

    @Value("${only-office.domain:#{null}}")
    public String domain;

    @Value("${spring.resources.context:#{'/'}}")
    protected String contextPath;

    @Resource
    protected FileClientFactory fileClientFactory;

    @Override
    public String handle(FileAttribute fileAttribute, HttpServletRequest request, Model model, boolean edit) {
        String fileName = fileAttribute.getName();
        String suffix = FileUtil.getFileSuffix(fileName);

        try {
            if (FileUtil.checkDocType(fileName)) {
                model.addAttribute("documentType", "word");
            } else if (FileUtil.checkExcelType(fileName)) {
                model.addAttribute("documentType", "cell");
            } else if (FileUtil.checkPPTType(fileName)) {
                model.addAttribute("documentType", "slide");
            } else {
                throw new ServerException(I18nUtil.message(ExceptionConstants.MEDIA_TYPE));
            }

            model.addAttribute("domain", domain);
            model.addAttribute("fileType", suffix.toLowerCase());
            model.addAttribute("title", FileUtil.getFilePrefix(fileName));
            model.addAttribute("key", fileAttribute.getKey());
            model.addAttribute("url", fileAttribute.getUrl());
            model.addAttribute("callbackUrl", ServletUtil.getRequestPrefix(contextPath) + "office/callback");
            model.addAttribute("edit", edit);
            model.addAttribute("operator", edit ? "在线编辑" : "在线预览");
            return "/file/office";
        } catch (Exception e) {
            model.addAttribute("fileType", suffix);
            model.addAttribute("msg", e.getMessage());
            return "/file/fileNotSupported";
        }
    }
}
